package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> list2Tree() {
        //1.查询所有分类数据
        List<CategoryEntity> list = baseMapper.selectList(null);
        //2.组装分类数据
        /**
         * 首先过滤出所有一级数据
         */
        List<CategoryEntity> root = list.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(menu -> {
                   //根据当前menu的父id找到子集
                    menu.setChildren(getChildren(menu, list));
                    return  menu;
                })
                .collect(Collectors.toList());

        return root;
    }

    /**
     * 根据分类id，查询级联ID
     * @param categoryId
     * @return
     */
    @Override
    public Long[] findCategoryIds(Long categoryId) {
        log.info("分类id:{}", categoryId);
        if(!StringUtils.isEmpty(categoryId)){

        }

        List<Long> list = new ArrayList<>();
        //递归查询父级
        //查找到的级联ids,由于是从最末节点查找，所以id是倒序的，需做一个反转
        List<Long> parentById = findParentById(categoryId, list);
        //parentById 反转
        Collections.reverse(parentById);
        //转成Long数组
        Long[] ids = parentById.toArray(new Long[parentById.size()]);
        return ids;
    }

    /**
     * 保存分类信息  并且更新品牌和分类关联表的分类名称
     * @param category
     */
    @Override
    public void updateDetail(CategoryEntity category) {
        //根据分类ID，更新关联表中的分类名称
        UpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("catelog_id", category.getCatId());
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogName(category.getName());
        categoryBrandRelationService.update(categoryBrandRelationEntity, updateWrapper);
        //更新自己的数据
        this.updateById(category);
    }

    public List<Long> findParentById(Long categoryId, List<Long> list){
        //把当前分类id，存入到list
        list.add(categoryId);
        //根据分类id查询分类信息
        CategoryEntity categoryEntity = baseMapper.selectById(categoryId);
        if(categoryEntity.getParentCid() != 0){
            findParentById(categoryEntity.getParentCid(), list);
        }
        //把找到的级联id返回
        return list;
    }

    public List<CategoryEntity> getChildren(CategoryEntity currentMenu, List<CategoryEntity> all){
        //递归查找子集
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == currentMenu.getCatId();
        }).map(menu ->{
            //递归找到子集
            menu.setChildren(getChildren(menu, all));
            return menu;
        }).collect(Collectors.toList());
        return children;
    }

}